var app = angular.module('app', ['app.tool','ui.router','oc.lazyLoad']);
var token,userType,orgID,isDirect;
var PERMISSION = {},dspFinance = {};

// 配置白名单
app.config(function($sceDelegateProvider) {  
    $sceDelegateProvider.resourceUrlWhitelist([
        'self',
        'http://res1.hubcloud.com.cn/**',
        'https://res1.hubcloud.com.cn/**',
      ])
})

app.controller("indexCtrl",function($scope,proxy,$state){
    var agentID;
    $scope.$state = $state;
    $scope.oem = JSON.parse(localStorage.oem);

    
    token = localStorage.dspToken;
    userType = "dsp";

    getUser();
    hasOem();

    $scope.logout = function(){
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/user/logout',
            data: {
                loginName: $scope.loginName
            }
        })
        localStorage.token = "";
        location.href = "./login.html";
    }
	function logout(){
        localStorage.token = "";
        location.href = "login.html";
    }
    $(".nav_dropdown").css("width",document.body.clientWidth);
    document.body.onresize = function(){
        $(".nav_dropdown").css("width",document.body.clientWidth);
    }
    $(document).on("click",".close-layer",function () {
       layer.closeAll();
    });

    $scope.hover = false;
    $scope.hasDepot = false;
    $scope.hasReward = false;

    $scope.getBalnce = function(){
        $scope.hover = !$scope.hover;
        getBalnce();
    }
    // 修改密码
    $scope.resetPWD = function() {
        var pwd = $scope.pwd || {};
        if(!pwd.oldPasswd || !pwd.newPasswd || !pwd.newPasswd2) return layer.msg("请输入密码!");
        if(!pwd.oldPasswd) return layer.msg("请输入旧密码!");
        if(pwd.newPasswd != pwd.newPasswd2) return layer.msg("两次密码不一致!");
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/reset/passwd',
            load:true,
            data: {
                uid: localStorage.userId,
                oldPasswd: pwd.oldPasswd,
                newPasswd: pwd.newPasswd,
            },
            success: function(){
                $("#pwdModal").modal("hide")
                layer.msg("修改成功!");
            }
        })
    }
    // oem 
    $scope.hasOem = false;
    $scope.showOEM = function(){
            
       // 查询OEM信息
        proxy.proxy({
            'url': STATIC_URL.domian+'/dsp/user/oem/query/agency',
            'load':true,
            'data': {
                data:orgID 
            },
            success: function(res) {
                $scope.oemList = res.data;
                if($scope.oemList.length == 0) {
                    $scope.oemList.push({url:""}); 
                }
                var data = $scope.oemList;
                $scope.oemEdit = {
                    background: data[0].background || "",// 登陆页面背景图片
                    loginLogo: data[0].loginLogo || "",//登陆页面Logo地址
                    staticLogo: data[0].staticLogo || "",//导航栏Logo地址
                    sdkLogo: data[0].sdkLogo || "",//SDK Logo地址
                    iconUrl: data[0].iconUrl || "",//角标图片地址
                    title: data[0].title || "",//所有oem文字信息
                    copyright: data[0].copyright || "",//版权信息
                    adLogo: data[0].adLogo || "",
                    adLogoExt: data[0].adLogoExt || "",
                    adLogoUrl: data[0].adLogoUrl || "",
                    adLabel: data[0].adLabel || ""
                }
                $("#dspOemModal").modal();
            }
        })
    }
    $scope.addUrl = function() {
        $scope.oemList.push({url:""});  
    }
    $scope.removeUrl = function(index) {
        $scope.oemList.splice(index,1);
    }
    
    $scope.uploadImg = function (obj) {
        $scope.imgObj = obj;
        $("#upload").trigger("click");
    }
    $scope.saveOEM = function () {
        var oemInfos = [];
        var urlFlag = true;
        var reg = /^(https?:\/\/)|(\/)/;
        // 重组oemInfos数据
        $scope.oemList.forEach(function(v,i){
            if(v.url) {
                var obj = angular.copy($scope.oemEdit)
                if(v.url.match(reg))  return urlFlag = false
                obj.url = v.url;
                obj.orgID = orgID;
                oemInfos.push(obj)
            }
        })
        if(!urlFlag) {
            return layer.msg("域名格式错误，禁止输入协议（http/https），禁止输入特殊字符（/）")
        }
        if(oemInfos.length == 0) return layer.msg("请输入自有域名！")
        //将重组好的数据替换
        $scope.oemList.oemInfos = oemInfos;
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/user/oem/update',
            load: true,
            data: {
                data: {
                    orgID: orgID,
                    oemInfos: oemInfos
                }
            },
            success: function() {
                layer.msg("修改成功");
                $("#dspOemModal").modal('hide')
            }
        })
    }
    $('[data-toggle="tooltip"]').tooltip()
    //提示信息显示
    $scope.tips = function (event,str) {
        layer.tips(str, $(event.target), {
            time: 1500,
            tips: [1, '#fffee3']
        });
    }
    
    function getUser(){
        // 基本信息
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/UserInfo',
            data: {
                type: userType
            },
            success: function(res){
                // 获得用户状态
                $scope.user = res.data;
                // 保存ID
                localStorage.userId = res.data.id;
                orgID = res.data.orgID;
            }
        })

        // 权限
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/pri/user/action',
            data: {},
            success: function(res){
                // 为PERMISSION对象添加属性  而不是直接将res.data赋值给PERMISSION
                // 可以防止在接口返回前使用PERMISSION导致拿不到权限内容
                if(!res.data){
                    res.data = {view:"",act:""}
                }
                PERMISSION.view = setData(res.data.view);
                PERMISSION.act = setData(res.data.act);
                function setData(arr) {
                    arr = arr || [];
                    for(var i = 0; i < arr.length; i++) {
                        var temp = arr[i];
                        arr[temp.name] = temp;
                        if(temp.sub) setData(temp.sub);
                    }
                    return arr;
                }
                $scope.permission = PERMISSION;
                $scope.$broadcast('permission', $scope.permission)
            }
        })

        // 奖励金
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/sys/parameter/query',
            data: {
                "filter":{"feature":"dsp.feature.reward.allow"},
            },
            success: function(res){
                $scope.hasReward = res.data[0].value == 1;
            }
        })
    }
    function getBalnce() {
        $scope.finance = {
            balance:"--"
        }
        
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/saas/dsp/finace/summary',
            data: {},
            success: function(res){
                $scope.finance = res.data;
            }
        })
    }
    function hasOem() {
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/sys/parameter/query',
            load: true,
            data: {
                "filter":{"feature":"dsp.feature.saas.dsp.oem.edit.self.allow"}
            },
            success: function(res){
                if(res.data && res.data[0].value == "1") {
                    $scope.hasOem = true;
                }
            }
        })
    }
    $('.icon-help').mouseleave(function(){
        layer.closeAll();
    })
    // 上传文件按钮
    fileUpload({
        'btnId': "upload",
        'funcUrl': '1',
        'FileUploaded':function(info){
            $scope.$apply(function(){
                $scope.oemEdit[$scope.imgObj.attr] = info.url;
            })
        },
        'BeforeUpload': function (up, file, next) {
            var nFile = file.getNative(),
                image = new Image(),
                size = $scope.imgObj.size,
                width = $scope.imgObj.width,
                height = $scope.imgObj.height;

            // 判断文件类型
            if($scope.imgObj.fileType != 'all') {
                if (!(/.png$/i).test(file.name)){
                    up.removeFile(file);
                    return layer.msg("格式错误，请上传png格式。")
                }
            }

            // 判断文件大小
            if(nFile.size >= size*1024) {
                up.removeFile(file);
                return layer.msg("文件不得大于"+size+"K")
            }

            if(width && height) {
                //加载图片获取图片真实宽度和高度
                image.onload= function() {
                    // 多种尺寸
                    if(typeof width == 'object') {
                        var flag = false;
                        for(var i = 0; i < width.length; i ++) {
                           // 判断图片比例
                            if(image.width == width[i] && image.height == height[i]){
                                flag = true;
                                break;
                            }
                        }
                        if(flag) {
                            next();
                        } else {
                            up.removeFile(file);
                            layer.msg("图片的尺寸不规范，请重新上传！")
                        }
                    } else { // 单种尺寸
                        // 判断图片比例
                        if(image.width != width || image.height != height){
                            up.removeFile(file);
                            layer.msg("图片的尺寸不是"+width+"x"+height+"，请重新上传！")
                        } else {
                            next();
                        }
                    }
                };
            } else {
                next();
            }

            image.src = window.URL.createObjectURL(nFile);
        }
    })
    $('#dspOemModal').on('shown.bs.modal', function (e) {
        // 关键代码，如没将modal设置为 block，则$modala_dialog.height() 为零
        $(this).css('display', 'block');
        var modalHeight=$(window).height() / 2 - $(this).find('.modal-dialog').height() / 2;
        $(this).find('.modal-dialog').css({
            'margin-top': modalHeight
        });
    });
})

// 跳转第一个链接
$(document).on("click",".nav_list .toFirstSub",function(){
    $(this).siblings("ul").find("a:eq(0)")[0].click();
})

